package com.mezz.bones.im.gateway.handler.codec;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.mezz.bones.im.common.result.ImResult;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author mezz
 * @date 2022-09-23 14:08
 * @description:
 * 统一响应对象 转换成 Websocket响应体
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class Encode2WebsocketHandler extends MessageToMessageEncoder<ImResult> {

  // 统一的日期格式配置，作为静态常量减少重复创建
  private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

  // 使用缓存的 ObjectMapper 进行序列化
  private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
          .setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY)
          .setSerializationInclusion(JsonInclude.Include.ALWAYS)
          .setDateFormat(new java.text.SimpleDateFormat(DATE_FORMAT))
          .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false)
          ;

  @Override
  protected void encode(ChannelHandlerContext channelHandlerContext, ImResult result, List<Object> list) throws Exception {
    log.debug("-----------Encode2WebsocketHandler begin-----------");

    if (result == null) {
      return;
    }

    // 使用 ObjectMapper 进行序列化
    String jsonString = OBJECT_MAPPER.writeValueAsString(result);
    list.add(new TextWebSocketFrame(jsonString));
  }
}
